package com.forezp.config;


import com.forezp.service.UserServiceDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by fangzhipeng on 2017/5/27.
 * (lgb) uaa-service服务是一个授权服务器，同时也是资源服务器 对外提供获取JWT的API接口 所以，需要配置该服务的Spring Security;
 * 因为需要对外暴露登录接口
 */

@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 向Ioc容器注入AuthenticationManager 这需要在OAuth2中配置，只有在OAuth2中配置了，密码验证才会开启。
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
            .and()
                .authorizeRequests()
                .antMatchers("/**").authenticated()
            .and()
                .httpBasic();
    }

    @Autowired
    UserServiceDetail userServiceDetail;
    /**
     * 在这里配置验证用户的用户信息源、密码加密策略
     * 在创建用户到数据库时，密码也需要使用该加密方式
     * 这里配置了验证用户信息源和密码加密的策略，
     * 这里认证的是 客户端id 和密码？
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userServiceDetail)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}
